package org.poem.time;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

/**
 *
 */
public class MultiplexerTimeServer implements Runnable {

  private Selector selector;

  private ServerSocketChannel serverSocketChannel;

  /** 线程可见 */
  private volatile boolean stop;

  public MultiplexerTimeServer(int port) {
    try {
      selector = Selector.open();
      serverSocketChannel = ServerSocketChannel.open();
      serverSocketChannel.configureBlocking(false);
      serverSocketChannel.socket().bind(new InetSocketAddress(port), 1024);
      serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    } catch (IOException e) {
      e.printStackTrace();
      System.err.println(e.getMessage());
      System.exit(1);
    }
  }

  public void stop() {
    this.stop = true;
  }

  @Override
  public void run() {
    while (!stop) {
      try {
        selector.select(1000);
        Set<SelectionKey> selectionKeys = selector.keys();
        Iterator<SelectionKey> iterable = selectionKeys.iterator();
        SelectionKey key = null;
        while (iterable.hasNext()) {
          key = iterable.next();
          iterable.remove();
          try {
            handleInput(key);
          } catch (Exception e) {
            if (key != null) {
              key.cancel();
              if (key.channel() != null) {
                key.channel().close();
              }
            }
          }
        }

      } catch (Throwable throwable) {
        throwable.printStackTrace();
      }
    }
    if (selector != null) {
      try {
        selector.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  /**
   * 多路复用器 所有注册在上面的chnnal 和Pipe 等资源都会自动去注册并关闭 不需要重复释放资源
   *
   * @param key
   * @throws IOException
   */
  private void handleInput(SelectionKey key) throws IOException {
    if (key.isValid()) {
      if (key.isAcceptable()) {
        // accept the new connection
        ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
        SocketChannel sc = ssc.accept();
        sc.configureBlocking(false);
        // add the new connection to the selector
        sc.register(this.selector, SelectionKey.OP_READ);
      }
      if (key.isReadable()) {
        // read the data
        SocketChannel sc = (SocketChannel) key.channel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        int readBytes = sc.read(byteBuffer);
        if (readBytes > 0) {
          byteBuffer.flip();
          byte[] bytes = new byte[byteBuffer.remaining()];
          byteBuffer.get(bytes);
          String body = new String(bytes, Charset.forName("UTF-8"));
          System.out.println("the time server reveice order:" + body);
          String currentTime =
              "Query Time Order".equals(body)
                  ? new java.util.Date(System.currentTimeMillis()).toString()
                  : "BAD ORDER";
          doWrite(sc, currentTime);
        } else if (readBytes < 0) {
          // 对端链路关闭
          key.cancel();
          sc.close();
        } else {
          ; //
        }
      }
    }
  }
  /**
   * 返回消息
   *
   * @param channel
   * @param response
   * @throws IOException
   */
  private void doWrite(SocketChannel channel, String response) throws IOException {
    if (response != null && response.trim().length() > 0) {
      byte[] bytes = response.getBytes();
      ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
      writeBuffer.put(bytes);
      writeBuffer.flip();
      channel.write(writeBuffer);
    }
  }
}
